package com.etc.demo.utils;

import org.springframework.boot.autoconfigure.integration.IntegrationProperties;

import java.sql.*;

/**
 * jdbc工具类
 * 单列模式
 */
public class JdbcUtils {
    //private JDBC 方法私有化 链接数据库
    //不能更改
    private static String url = "com.mysql.jdbc.Driver";
    private static String user = "root";
    private static String password = "12345678";
    private  static String driver = "jdbc:mysql://localhost:3306/test";

    /**
     * 文件读取，只会执行一次，使用静态代码块
     */
    static {
        //读取文件，获取值
        try {
            //4.注册驱动
            Class.forName(url);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return 连接对象
     */
    public static Connection getConnection() throws SQLException {
        Connection conn = DriverManager.getConnection(driver, user, password);
        return conn;
    }

    /**
     * 释放资源
     * @param rs
     * @param st
     * @param conn
     */
    public static void close(ResultSet rs, Statement st, Connection conn){
        if (rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(st != null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }



}
